<template>
    <h1>修改菜品</h1>
    <el-button @click="router.push('/dish')" type="primary">&lt;返回</el-button>
  
    <div class="content">
    <div class="row"> <span class="font">菜品名称:</span><el-input class="dish" v-model="name"></el-input><br></div>
    <div  class="row"><span class="font"> 菜品分类:</span>
      <el-select v-model="catego" placeholder="选择分类">
         <el-option v-for="(item,index) in category" :lable="item" :key="index" :value="item"></el-option>
      </el-select>
      
      <br></div> 
    <div  class="row"> <span class="font">菜品价格:</span><el-input class="dish" v-model="price" type="number"></el-input></div> 
    </div>
   
   <!-- 口味 -->
   <div class="kouwei">
    <div class="kouwei-txt">口味做法配置:</div>
      
    <div class="kouwei-div">
        <div class="kouwei-two">口味名（3个字内） &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;口味标签</div>
     <el-scrollbar>
       <li  v-for="(it,idx) in data" :key="idx">
          <el-select class="select"
            v-model="data[idx].kouwei"
            placeholder="选择口味"
            clearable
           >
            <el-option v-for="(item,index) in kounames"  :label="item" :key="index" :value="item" 
            @click="setKouwei(item,idx)"/>
         </el-select>
         <!-- 标签 -->
          <div class="tag">
            <el-tag
                    v-for="(tag,id) in it.tag"
                    :key="id"
                    class="mx-1"
                    closable
                    :type="random[id]"
                    :disable-transitions="false"
                    @close="handleClose(tag,id,idx)"
                >
                    {{ tag }}
                </el-tag>
              <!--添加标签 -->
            <el-select placeholder="添加" style="width: 70px;">
             <el-option v-for="(item,index) in tagNames" :lable="item" :key="index" :value="item"
              @click="addTag(item,idx)"></el-option>
           </el-select>
      



                <!-- <el-input
                    v-if="it.inputshow"
                    ref="InputRef"
                    v-model="inputValue"
                    class="ml-1 w-20"
                    size="small"
                    @keyup.enter="handleInputConfirm(idx)"
                    @blur="handleInputConfirm(idx)"
                />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(idx)">
                    + 添加
                </el-button> -->
          </div>
          <a href="javascript:;" class="del" @click="deleteOne(idx)">删除</a>
       </li>
      </el-scrollbar> 
       <!-- 添加口味按钮 -->
       <el-button type="primary" class="addbutton" @click="addKouwei">添加口味</el-button>

    </div>
    

   </div>

<!-- 图片上传 -->
 <div class="imgarea">
  <div>菜品图片</div>
  <el-upload
        class="avatar-uploader"
        :action="dishImgUploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="dishImgDoUrl" :src="dishImgDoUrl" class="avatar" style="width: 240px;height: 200px;margin-left: 200px;" />
        <el-icon v-else class="avatar-uploader-icon" style="width:240px;height: 200px;margin-left: 200px;
        border: 1px solid black;"><Plus /></el-icon>
      </el-upload>
   <div class="img-txt">
     <div>图片大小不超过2M</div>
     <div>仅能上传 PNG JPEG JPG类型图片</div>
   </div>

 </div>
 <!-- 状态选择 -->
 <div style="margin-top: 20px;">售卖状态</div>
<el-switch
    v-model="statusFlag"
    class="ml-2"
    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;
    margin-left: 100px;"
  />

<!-- 菜品描述 -->
<div class="desc">
  <div class="desc-title">菜品描述:</div>
  <div>
    <el-input
    style="width: 900px;margin-left: 100px;"
    v-model="description"
    :autosize="{ minRows: 4, maxRows: 6 }"
    type="textarea"
    placeholder="请输入菜品描述..."
  />
  </div>
</div>

<div class="submit">
  <el-button type="primary" class="sub" @click="addOne">保存</el-button>
</div>


 <!-- 删除对话框 -->
 <el-dialog
     v-model="delVisable"
     title="删除口味"
     width="30%"
     align-center
   >
     <span>你确定要删除该口味吗?</span>
     <template #footer>
       <span class="dialog-footer">
         <el-button @click="delVisable = false">取消</el-button>
         <el-button type="primary" @click="deleteKouwei">
           确定
         </el-button>
       </span>
     </template>
   </el-dialog>

<!-- 图片展示对话框 -->
<el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
</el-dialog>


</template>


<script setup lang="ts">
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ref } from 'vue';
import { ElInput, UploadProps, alertProps } from 'element-plus';
import { onMounted } from 'vue';
import {ElMessage}from 'element-plus'
import categoryApi from '@/api/category';
import flavourApi from '@/api/flavour';
import dishApi from '@/api/dish'
import tagApi from '@/api/tag';
import {dishImgUploadUrl,dishImgUrl} from '@/config/imgconfig'



const router = useRouter()
const store = useStore()

//口味详细信息
const kouweis = ref([])
//口味的名称
const kounames = ref([])
//菜品分类 
const category = ref([])
//这个是详细的信息，为了之后添加菜品时添加对应的分类信息
const categoryInfos = ref([])
//标签数据
const tags = ref([])
//标签名称
const tagNames = ref([])

//口味以及标签数据

const data = ref([
{
  kouwei:'',
  tag:[],
  //inputshow:false
}])

const did = ref(0)

//加载页面数据
onMounted(()=>{
  did.value =  store.state.dishId;
  //先给页面上的东西设置一下数据把
  setDatas(store.state.dishId);
  getDishCate(),
  getFlavours(),
  getTags()
})

//获取菜品原始数据
 async function setDatas(id:Number) {
    const res = await dishApi.getDishFlavourTags(id);
    if(res.code===200){
        name.value = res.data.dish.name
        price.value = res.data.dish.price
        catego.value = res.data.dish.category
        dishImgDoUrl.value = dishImgUrl + res.data.dish.img
        description.value = res.data.dish.description
        dishImgName.value = res.data.dish.img
        //对口味标签进行处理
        //先把data清空
        
        res.data.flavourTags.forEach(it=>{
            var tags = JSON.parse(it.tags)
            data.value.push({
                kouwei:it.kouwei,
                tag:tags
            })
        })
        data.value.splice(0,1)
    }
 }



//获取口味数据
async function getFlavours(){
    const data = await flavourApi.getFlavour()
    if(data.code===200){
        kouweis.value = data.data
        //过滤出来名称
        const fNames:[] = data.data.map((it: { flavour: any; })=>it.flavour)
        fNames.forEach(it=>{
           kounames.value.push(it)
        })
        
    }else{
      ElMessage({"message":data.data,"type":"error"})
    }
}

//获取菜品分类数据
async function getDishCate(){
   const data = await categoryApi.getDishCate()
   if(data.code===200){
      categoryInfos.value = data.data;
        data.data.forEach((item: any) => category.value.push(item.name))
   }else{
     ElMessage({"message":data.data,"type":"error"})
   }
 
}
//获取标签数据
async function getTags() {
  const data = await tagApi.getTags()
  if(data.code===200){
        tags.value = data.data
        //过滤名称
        const tNames = data.data.map((it:{tag:any;})=>it.tag)
         tNames.forEach((it: any)=>{
           tagNames.value.push(it)
         })
         console.log(tagNames.value);
    }else{
      ElMessage({"message":data.data,"type":"error"})
    }
}



//菜品的数据
const name = ref('')
const price = ref(0)
const catego = ref('')
const description = ref('')
//状态判断标志
const statusFlag = ref(true)


//设置口味
const setKouwei=(item:string,index:number)=>{
   data.value[index].kouwei = item
}
//添加标签
const addTag=(item: any,index:number)=>{
   if(!data.value[index].tag.includes(item)){
     data.value[index].tag.push(item)
   }else{
     ElMessage({"message":"已存在该标签!","type":"warning"})
     return;
   }
}
//删除标签
const handleClose = (tag: string,id:number,idx:number) => {
  data.value[idx].tag.splice(id,1)
}


//标签的输入值
const inputValue = ref('')


const InputRef = ref<InstanceType<typeof ElInput>>()


//展示标签
const showInput = (idx:number) => {

    data.value[idx].inputshow = true

}
//输入完标签确定
const handleInputConfirm = (idx:number) => {
  if (inputValue.value) {
    data.value[idx].tag.push(inputValue.value)
  }
  data.value[idx].inputshow = false
  inputValue.value = ''
}









//随机标签颜色
var random = ref(['success','warning','danger','info','default','success'])


//删除对话框的标志
const delVisable = ref(false)
const delIndex = ref(0)
//删除一行
const deleteOne = (index:number)=>{
  delVisable.value = true
  delIndex.value = index
}
const deleteKouwei=()=>{
  //删除该行
  data.value.splice(delIndex.value,1)
  delVisable.value = false;
  deleteMsg()
}

//添加口味
const addKouwei=()=>{

  data.value.push({
     kouwei:'',
     tag:[]
  })
}

const deleteMsg = () => {ElMessage({ message: '已删除该口味',type: 'success', })}

//菜品图片的名称
const dishImgName = ref('')
//菜品图片下载地址
const dishImgDoUrl = ref('')

//图片上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
 
 // if(ImgName.value!=''||ImgName.value!=null){
 //      imgApi.deleteUserImg(ImgName.value)
 //    }


 if (rawFile.type !== 'image/jpeg') {
   ElMessage.error('图片格式必须是jpg')
   return false
 } else if (rawFile.size / 1024 / 1024 > 2) {
   ElMessage.error('图片大小不能大于2MB')
   return false
 }
 return true
}
//图片上传成功之后的操作
const handleAvatarSuccess: UploadProps['onSuccess'] = (
 response,
 uploadFile
) => {
  dishImgName.value = response.data
 //console.log(ImgName.value);
  dishImgDoUrl.value= URL.createObjectURL(uploadFile.raw!)
}

//判断一个对象是否是数字
function isNumber(value: any) {
  return typeof value === 'number' && !isNaN(value);
}

//添加菜品
async function addOne(){
  //检查名称是否为空
  if(name.value===''||name.value===null || name.value===undefined){
      
    ElMessage({"message":"菜品名称不能为空","type":"warning"})
    return
  } 
  if(catego.value===''||catego.value===null || catego.value===undefined){
    ElMessage({"message":"分类不能为空","type":"warning"})
    return;
  }
  if(price.value===''||price.value===null || price.value===undefined ){
    ElMessage({"message":"价格不能为空","type":"warning"})
    return
  }
  // if(isNumber(price.value)==false){
  //    ElMessage({"message":"价格必须是数字类型","type":"warning"})
  //    return 
  // }
 
  data.value.forEach(it=>{
    if(it.kouwei===''||it.kouwei===null || it.kouwei===undefined){
      ElMessage({"message":"口味不能为空","type":"warning"})
      return;
    }
  })
  if(dishImgName.value===''||dishImgName.value===null || dishImgName.value===undefined){
    ElMessage({"message":"图片不能为空","type":"warning"})
    return 
  }
  
  //添加菜品
  //构建菜品对象
  const dishDto = {
    id:did.value,
    name:name.value,
    img:dishImgName.value,
    price:price.value,
    category:catego.value,
    description:description.value,
    status:statusFlag.value==true?"在售":"停售",
    //口味标签列表
    flavourTags:data.value
  }
  //添加
  const res = await dishApi.updateDish(dishDto)
  if(res.code===200){
    ElMessage({"message":res.data,"type":"success"})
  }else{
    ElMessage({"message":res.data,"type":"error"})
  }



}





</script>


<style scoped lang="less">

li{
    list-style: none;
}
a{
    text-decoration: none;
    color: black;
}
a:hover{
    color: rgb(95, 93, 91);
}

.content{
  
  margin-left: 100px;
}
.dish{
    width: 300px;
}

.row{
    margin-top: 20px;
  
 .font{
    margin-right: 20px;
 }
}
.kouwei{
    margin-top: 50px;

   .kouwei-txt{
      margin-left: 30px;
   }
   .kouwei-div{
      width: 900px;
      height: 150px;
      border: 1px solid black;
      border-bottom: none;
      margin-left: 150px;
     .kouwei-two{
      margin-top: 10px;
      margin-left: 10px;
   }
   .select{
     float: left;
     margin-left: 10px;
   }
   .tag{
     float: left;
     width: 500px;
     height: 33px;
     background-color: white;
     margin-left: 20px;
     margin-bottom: 5px;
     padding-top: 5px;
     padding-left: 10px;
     .el-tag{
        margin-right: 10px;
     }

   }
   .del{
       display: block;
       margin-bottom: 20px;
        
      
   }
}
}

//标签输入框
.ml-1{
  width: 60px;
}

//添加口味按钮
.addbutton{
  margin-top: 10px;
  margin-right: 350px;
  margin-left: 20px;
}

//图片区域
.imgarea{
   
  margin-top: 100px;
  
 .upload{
  margin-left: 150px;
 }
 .img-txt{
   position: absolute;
   margin-left: 350px;
   bottom: 1px;
 }
}

//保存按钮
.submit{
   margin-top: 20px;
   margin-left: 400px;
   margin-bottom: 100px;
   .sub{
     margin-bottom: 30px;
   }
}


</style>